package io.renren.modules.app.service.impl;

import io.renren.modules.app.dao.SubjectCategoryDao;
import io.renren.modules.app.entity.AnswerEntity;
import io.renren.modules.app.entity.SubjectResultEntity;
import io.renren.modules.app.entity.SubjectCategoryEntity;
import io.renren.modules.app.entity.SubjectTypeEnum;
import io.renren.modules.app.service.BusinessService;
import io.renren.modules.app.service.SubjectCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private SubjectCategoryService subjectCategoryService;

    @Override
    public List<SubjectCategoryEntity> getSubjectCategory() {
        List<SubjectCategoryEntity> subjectCategory = subjectCategoryService.getSubjectCategory();
        return subjectCategory;
    }

    @Override
    public List<SubjectResultEntity> getSubjectResult(List<AnswerEntity> answers) {
        //判断是否已支付

        Map<String, List<AnswerEntity>> typeMap = answers.stream().collect(Collectors.groupingBy(AnswerEntity::getAnswerType));
        Map<String, String> goalMap = new HashMap<>();
        for (Map.Entry<String, List<AnswerEntity>> typeEntry : typeMap.entrySet()) {
            String type = typeEntry.getKey();
            List<AnswerEntity> typeAnswers = typeEntry.getValue();
            Byte fullCredit = typeAnswers.stream().findAny().get().getFullCredit();
            Integer goals = typeAnswers.stream().map(typeAnswer -> {
                if (typeAnswer.getAnswerType().equals("0")) {
                    return typeAnswer.getSubjectAnswer();
                } else {
                    return typeAnswer.getFullCredit() - typeAnswer.getSubjectAnswer() + 1;
                }
            }).reduce(Integer::sum).get();
            double goal = (double) goals / typeAnswers.size() * 100/fullCredit;
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(0);
            String goalFormat = numberFormat.format(goal);
            goalMap.put(type, goalFormat);
        }
        //根据结果判断有趣类型
        List<SubjectResultEntity> subjectResultEntities = new ArrayList<>();
        for (Map.Entry<String, String> goalEntry : goalMap.entrySet()) {
            SubjectResultEntity subjectResultEntity = new SubjectResultEntity();
            String type = goalEntry.getKey();
            String goal = goalEntry.getValue();
            subjectResultEntity.setType(type);
            subjectResultEntity.setGoal(goal);
            subjectResultEntity.setDesc(SubjectTypeEnum.getDesc(type));
            subjectResultEntities.add(subjectResultEntity);
        }
        return subjectResultEntities;
    }
}
